//
//  PBAppDelegate.m
//  Bus
//
//  Created by wangjiajia on 13-7-6.
//  Copyright (c) 2013年 wangjiajia. All rights reserved.
//

#import "PBAppDelegate.h"

#import "PBLoginViewController.h"
#import "NewsView.h"
#import "OneDayView.h"
#import "NoticeView.h"
#import "ProfitView.h"
#import "WorkReportView.h"
#import "UIImage+UIImageExtras.h"

#import "Config.h"
#import "Tools.h"
#import "Gtasks.h"
#import "UIButton+Bootstrap.h"

#import "WebServicesUtils.h"
#import "ASIHTTPRequest.h"
#import "JsonParser.h"

@implementation PBAppDelegate{
    //最后一个点击页即为当前页
    int currentPage;
    BOOL isSuper;//是否是超级用户
    //待办任务
    UINavigationController *gtasksNav;
    NSArray* workflowButtons;
}

//- (void)dealloc
//{
//    [_window release];
//    [_pbLoginViewController release];
//    [super dealloc];
//}
#pragma mark --程序生命周期函数
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    
    
    //显示系统托盘
    //[application setStatusBarHidden:NO withAnimation:UIStatusBarAnimationFade];
    
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] ;
    // Override point for customization after application launch.
    //初始化登陆界面
    self.pbLoginViewController = [[PBLoginViewController alloc] initWithNibName:@"PBLoginViewController" bundle:nil];
    /*
     //初始化导航为登陆界面
     self.navController=[[[UINavigationController alloc] initWithRootViewController:self.pbLoginViewController] autorelease];
     //设置根控制器为导航
     self.window.rootViewController = self.navController;
     */
    
    self.window.rootViewController=_pbLoginViewController;
    [self.window makeKeyAndVisible];
    //修改标题栏字体等
    NSShadow *shadow = [[NSShadow alloc] init];
    shadow.shadowColor = [UIColor colorWithRed:0 green:0 blue:0 alpha:0.8];
    shadow.shadowOffset = CGSizeMake(0, 1);
    
    [[UINavigationBar appearance] setTitleTextAttributes: [NSDictionary dictionaryWithObjectsAndKeys:
                                                           
                                                           UIColorFromRGB(0x000000),NSForegroundColorAttributeName, shadow, NSShadowAttributeName,
                                                           [UIFont fontWithName:@"-" size:22.0], NSFontAttributeName, nil]];
    //NSLog(@">>>进入程序，userId=%d；userName=%@",userId,userName);
    
    return YES;
}


- (void)applicationWillResignActive:(UIApplication *)application
{
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}

- (void)applicationWillEnterForeground:(UIApplication *)application
{
    // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    
    [Config instance].isNetworkRunning=[Tools isExistenceNetwork];
    
    if ([Config instance].isNetworkRunning == NO) {
        UIAlertView *myalert = [[UIAlertView alloc] initWithTitle:@"警告" message:@"未连接网络,请连接网络后重试!" delegate:self cancelButtonTitle:@"确认" otherButtonTitles:nil,nil];
        [myalert show];
    }
}

- (void)applicationWillTerminate:(UIApplication *)application
{
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}
#pragma mark --自定义函数

-(void)goMainView:(int)ret{
    //self.pbLoginViewController=nil;//销毁？
    //NSLog(@"登陆成功，进入主界面");
    //添加广播处理：刷新待办工作个数
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTodoNum:) name:@"refresh_todonum" object:nil];
    //首次刷新工作个数
    [WebServicesUtils getExecSingle:[NSString stringWithFormat:@"getTodoNum @userId=%d",userId] andTag:1 withDelegete:self];
    
    //待办按钮 多个。不公用一个，因为实测发现，最后一个可以显示及点击。之前的只可以点击，但不显示。
    UIButton *workflowButton1 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
    //workflowButton1.titleLabel.textColor=[UIColor blackColor];not work
    //图片资源不好。。。。
    //[workflowButton1 setBackgroundImage:[UIImage imageNamed:@"news_bg"] forState:UIControlStateNormal];
    //[workflowButton1 setBackgroundImage:[UIImage imageNamed:@"button"] forState:UIControlStateHighlighted];
    UIButton *workflowButton2 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
    UIButton *workflowButton3 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
    UIButton *workflowButton4 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
    UIButton *workflowButton5 = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 80, 30)];
    
    workflowButtons=@[workflowButton1,workflowButton2,workflowButton3,workflowButton4,workflowButton5];
    for(UIButton* workflowButton in workflowButtons){
        [workflowButton clearStyle];
        workflowButton.titleLabel.font=[UIFont fontWithName:@"-" size:18];
        [workflowButton setTitle:@"待办" forState:UIControlStateNormal];
        [workflowButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [workflowButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [workflowButton addTarget:self action:@selector(goWorkFlow:) forControlEvents:UIControlEventTouchUpInside];
    }
    
    UIBarButtonItem *workflow1 = [[UIBarButtonItem alloc] initWithCustomView:workflowButton1];
    UIBarButtonItem *workflow2 = [[UIBarButtonItem alloc] initWithCustomView:workflowButton2];
    UIBarButtonItem *workflow3 = [[UIBarButtonItem alloc] initWithCustomView:workflowButton3];
    UIBarButtonItem *workflow4 = [[UIBarButtonItem alloc] initWithCustomView:workflowButton4];
    UIBarButtonItem *workflow5 = [[UIBarButtonItem alloc] initWithCustomView:workflowButton5];
    
    //1、IPHONE4/4S-3.5inch ; IPHONE5-4.0inch;
    //2、新闻中心（3.5inch tableveiew自动拉伸？不用改？）
    //3、默认的话，如果你的界面上包含scrollview/TableView等的话，这个界面基本上是不用改  的，因为中间部分会自动拉伸（3.5->4.0,高度自动增加88单位）。如果不包含这两个全屏的控件的话，怕是要自已再添加一个专门针对iPhone5的xib了。办法很简单，新建一个xib文件，将里面view的size设置成Retina 4 Full Screen就可以了。根据IS_IPHONE5来加载不同的控件
    //4、这里优先适配Retina 4 Full Screen
    //5、实测发现，只要背景设置成320*568,XIB为3.5或4.0都行,自动拉伸嘛。
    self.newsView=[[NewsView alloc] initWithNibName:@"NewsView" bundle:nil];
    //指定标题、图标
    self.newsView.tabBarItem.title=@"新闻中心";
    self.newsView.tabBarItem.image=[UIImage imageNamed:@"tab_newshome_select"];
    self.newsView.navigationItem.rightBarButtonItem =workflow1;
    UINavigationController * newsNav=[[UINavigationController alloc] initWithRootViewController:self.newsView];
    
    self.oneDayView=[[OneDayView alloc] initWithNibName:@"OneDayView" bundle:nil];
    self.oneDayView.tabBarItem.title=@"公交一天";
    self.oneDayView.tabBarItem.image=[UIImage imageNamed:@"tab_oneday_select"];
    self.oneDayView.navigationItem.rightBarButtonItem = workflow2;
    UINavigationController *oneDayNav=[[UINavigationController alloc] initWithRootViewController:self.oneDayView];
    
    
    self.noticeView=[[NoticeView alloc] initWithNibName:@"NoticeView" bundle:nil];
    self.noticeView.tabBarItem.title=@"通知公告";
    self.noticeView.tabBarItem.image=[UIImage imageNamed:@"tab_notice_select"];
    self.noticeView.navigationItem.rightBarButtonItem = workflow3;
    UINavigationController *noticeNav=[[UINavigationController alloc] initWithRootViewController:self.noticeView];
    
    
    self.profitView=[[ProfitView alloc] initWithNibName:@"ProfitView" bundle:nil];
    self.profitView.tabBarItem.title=@"财务查询";
    self.profitView.tabBarItem.image=[UIImage imageNamed:@"tab_profit_select"];
    self.profitView.navigationItem.rightBarButtonItem = workflow4;
    UINavigationController *profitNav=[[UINavigationController alloc] initWithRootViewController:self.profitView];
    
    self.workReportView=[[WorkReportView alloc] initWithNibName:@"WorkReportView" bundle:nil];
    self.workReportView.tabBarItem.title=@"工作汇报";
    self.workReportView.tabBarItem.image=[UIImage imageNamed:@"tab_workrep_select"];
    self.workReportView.navigationItem.rightBarButtonItem = workflow5;
    UINavigationController *workReportNav=[[UINavigationController alloc] initWithRootViewController:self.workReportView];
    
    //初始化UITabBar
    self.tabBarController=[[UITabBarController alloc] init];
    self.tabBarController.delegate=self;
    
    //判断权限，设置显示的控制器。
    if(ret==3){//兰总
        isSuper=YES;
        self.tabBarController.viewControllers=[NSArray arrayWithObjects:newsNav,oneDayNav,noticeNav,profitNav,workReportNav, nil];
    }
    else if(ret==1){//屌丝
        isSuper=NO;
        self.tabBarController.viewControllers=[NSArray arrayWithObjects:newsNav,oneDayNav,noticeNav,workReportNav, nil];
    
    }
    
    //修改界面下方的tabBar的背景
    self.tabBarController.tabBar.backgroundImage=[UIImage imageNamed:@"list_bg49"];//1、直接用高度为49的背景图片
    //self.tabBarController.tabBar.backgroundImage=[[UIImage imageNamed:@"list_bg"] imageByScalingToSize:CGSizeMake(self.tabBarController.tabBar.frame.size.width,self.tabBarController.tabBar.frame.size.height)];//2、通过缩放，但缩放效果不理想
    
    ////NSLog(@"tabBarController tabBar width=%f,height=%f",self.tabBarController.tabBar.frame.size.width,self.tabBarController.tabBar.frame.size.height);//320/49
    //[self.tabBarController.tabBar sizeToFit];
    self.window.rootViewController=self.tabBarController;
    
}

-(void)goWorkFlow:(id)sender{
    //不得不说 UINavigationController UIViewController 搞得我晕死了！！！
    //NSLog(@"进入待办工作");
    if(self.gtasks==nil){
        //NSLog(@"初始化待办工作");
        self.gtasks=[[Gtasks alloc] init];
        //自定义的下拉列表初始化没用。。。。哎。。。。
        // self.gtasks.dropDown=[[DropDownView alloc] initWithFrame:CGRectMake(0, 0, 320, 56)];//基于xib 不需要alloc
        // self.gtasks.dropDown.textField.placeholder=@"选择待办工作类型";
        // self.gtasks.dropDown.tableArray=[[NSArray alloc] initWithObjects:@"1",@"2",@"3", nil];
        
        //UIButton *b=(UIButton*)sender;
        ////NSLog(@"tag=%d",b.tag);
        
        //导航栏包裹，添加一个导航框
        gtasksNav=[[UINavigationController alloc] initWithRootViewController:self.gtasks];
        // UINavigationController *gtasksNav=self.gtasks.navigationController;
        //1、设置导航栏的背景(也可以在Gtask的viewDidLoad中设置背景图)
        UIImage *bgBarImg=[UIImage imageNamed:@"list_bg64"];
        
        //CGSize barSize=CGSizeMake(gtasksNav.navigationBar.frame.size.width, gtasksNav.navigationBar.frame.size.height);
        ////NSLog(@"%@",NSStringFromCGSize(barSize));//320*44
        //UIImage *bgBarImg=[[UIImage imageNamed:@"list_bg"] imageByScalingToSize:barSize];
        
        [gtasksNav.navigationBar setBackgroundImage:bgBarImg forBarMetrics:UIBarMetricsDefault];
        
        //2、UIViewController设置标题(基于导航框才可见)
        self.gtasks.navigationItem.title=@"待办工作";
        
        //3、UIViewController设置返回按钮(基于导航框才可见)
        UIButton *leftButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 60, 30)];
        
        [leftButton setBackgroundImage:[UIImage imageNamed:@"brown_titlebar_back.png"] forState:UIControlStateNormal];
        [leftButton setBackgroundImage:[UIImage imageNamed:@"brown_titlebar_back_selected.png"] forState:UIControlStateHighlighted];
        
        [leftButton setTitle:@" 返回" forState:UIControlStateNormal];
        leftButton.titleLabel.font=[UIFont fontWithName:@"-" size:18];
        [leftButton setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
        [leftButton setTitleColor:[UIColor whiteColor] forState:UIControlStateHighlighted];
        [leftButton addTarget:self action:@selector(backToTabControll:) forControlEvents:UIControlEventTouchUpInside];
        UIBarButtonItem *back = [[UIBarButtonItem alloc] initWithCustomView:leftButton];
        self.gtasks.navigationItem.leftBarButtonItem=back;
    }
    
    //进入新篇章
    //self.window.rootViewController=self.gtasks;
    self.window.rootViewController=gtasksNav;
    //[self.window.rootViewController.navigationController pushViewController:gtasksNav animated:YES];
    
    //隐藏下面工具栏（基础+积累+实践）
    // self.tabBarController.hidesBottomBarWhenPushed=YES;//无效，网查，self要换成具体push进的navicationController.可以这里设置 或 具体UI的viewWillAppear中设置
    //方式一
    //gtasts.tabBarController.hidesBottomBarWhenPushed=YES;
    //方式二，直接变黑
    //self.tabBarController.tabBar.hidden=YES;
    //方式三，模态方式显示，类似Android popWindow
    //    gtasts.navigationController.modalPresentationStyle=UIModalPresentationFormSheet;
    //    gtasts.navigationController.modalTransitionStyle=UIModalTransitionStylePartialCurl;
    //   [self.newsView.navigationController presentModalViewController:gtasts animated:YES];
    
    
}

-(void)backToTabControll:(id)sender{
    self.window.rootViewController=self.tabBarController;
}
-(void)refreshTodoNum:(NSNotification * )notification{
    [WebServicesUtils getExecSingle:[NSString stringWithFormat:@"getTodoNum @userId=%d",userId] andTag:1 withDelegete:self];
    
}
#pragma mark --重写 判断Tab点击
-(void)tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController{
    int newTabIndex = self.tabBarController.selectedIndex;
    if (newTabIndex == currentPage) {
        //NSLog(@"点击了当前页 %d",newTabIndex);
        //1、如果点击的页面为最后页面，即当前页面
        //2、点击当前页，作手动刷新处理
        //3、发送通知给所有接收器，让对应的Tab更新数据
        //4、接收器通过newTabIndex参数判断是否处理，最终只有对应的Tab更新数据
        //5、Notification_TabClick是唯一标示符
        //A、普通用户有4个标签,索引为:0、1、2、3(对应3，没响应，不符合实际要求)
        //B、兰总有5个标签,索引为:0，1，2，3(对应3，没响应，符合实际要求)，4。
        //C、即响应索引的只有0,1,2,4。3没有响应。所以，普通用户的3要重定向为4.
        if(!isSuper&&newTabIndex==3){
            newTabIndex=4;
        }
        [[NSNotificationCenter defaultCenter] postNotificationName:@"Notification_TabClick" object:[NSString stringWithFormat:@"%d", newTabIndex]];
    }
    else
    {
        //NSLog(@"点击了新页 %d",newTabIndex);
        currentPage = newTabIndex;
    }
    
}

#pragma mark- 处理网络请求
-(void)requestFinished:(ASIHTTPRequest *)request{
    NSString * responseStr=[request responseString];
    NSString* totalNum=[JsonParser parseAsTotalNum:responseStr];
    //NSLog(@"待办有%@条",totalNum);
    for(UIButton* workflowButton in workflowButtons){
        [workflowButton setTitle:[NSString stringWithFormat:@"待办(%@)",totalNum]forState:UIControlStateNormal];
    }
}
@end

